const { defineConfig } = require('@vue/cli-service')
const bodyParser = require('body-parser')
const Mock = require('mockjs')
// 模拟数据

const data = Mock.mock({
  'list|30': [
    {
      'id|+1': 1,
      provice: '@province()',
      'children|15': [
        {
          id: '@id()',
          city: '@city()',
        },
      ],
    },
  ],
})

const cart = Mock.mock({
  'list|50': [
    {
      'id|+1': 1,
      img: '@image(100x100, @color, @city)',
      name: '@cname',
      count: 0,
      checked: false,
      price: '@integer(10, 100)',
    },
  ],
})

// 这个文件，一更新，就要重新启动
module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    // 拦截中间件 可以在这个地方写express 的东西
    setupMiddlewares: (middlewares, { app }) => {
      // 配置
      app.use(bodyParser.json())

      const userInfo = [
        {
          user: 'devin',
          pwd: '123',
        },
        {
          user: 'admin',
          pwd: '123',
        },
      ]

      // 登陆接口
      app.post('/api/login', (req, res) => {
        const { username, password } = req.body
        const loginStatus = userInfo.some(
          (v) => v.user === username && v.pwd === password
        )
        if (loginStatus) {
          res.send({
            code: 0,
            msg: 'success',
            data: {
              token: `${username}_123`,
            },
          })
        } else {
          res.send({
            code: -1,
            msg: 'fail',
          })
        }
      })

      // 购物车列表接口 （带分页功能）
      app.get('/api/cart', (req, res) => {
        const { page = 1, size = 5 } = req.query
        res.send({
          code: 0,
          msg: 'success',
          data: {
            total: cart.list.length,
            list: cart.list.slice((page - 1) * size, page * size),
          },
        })
      })

      // ----------------------------------->
      app.get('/api/get-test', (req, res) => {
        res.send({
          code: 0,
          msg: 'success',
          data: { query: req.query },
        })
      })

      app.get('/api/list', (req, res) => {
        res.send({
          code: 0,
          msg: 'success',
          data: data.list,
        })
      })

      app.post('/api/post-test', (req, res) => {
        res.send({
          code: 0,
          msg: 'success',
          data: { body: req.body },
        })
      })
      return middlewares
    },
  },
})
